// stores/useAccountStore.js
import { defineStore } from 'pinia'

export const useAccountStore = defineStore({
  id: 'account',
  state: () => ({
    uid: null,
    token: '',
    type: '', // 可为 'user' 1 / 'admin'2
    username: '',
  }),
  actions: {
    // 设置用户信息并缓存到 localStorage
    setAccount({ uid, token, type, username }) {
      this.uid = uid
      this.token = token
      this.type = type
      this.username = username

      localStorage.setItem('uid', uid)
      localStorage.setItem('token', token)
      localStorage.setItem('type', type)
      localStorage.setItem('username', username)
    },

    // 清空用户信息
    clearAccount() {
      this.uid = null
      this.token = ''
      this.type = ''
      this.username = ''

      localStorage.removeItem('uid')
      localStorage.removeItem('token')
      localStorage.removeItem('type')
      localStorage.removeItem('username')
    },

    // 从 localStorage 恢复数据（App 启动时可调用）
    restoreFromLocalStorage() {
      const uid = localStorage.getItem('uid')
      const token = localStorage.getItem('token')
      const type = localStorage.getItem('type')
      const username = localStorage.getItem('username')

      if (uid && token && type) {
        this.uid = uid
        this.token = token
        this.type = type
        this.username = username
      }
    },
    initFromStorage() {
      const uid = localStorage.getItem('uid')
      const token = localStorage.getItem('token')
      const username = localStorage.getItem('username')
      const type = localStorage.getItem('type')

      if (uid && token) {
        this.uid = uid
        this.token = token
        this.username = username || ''
        this.type = type || ''
      }
    },
  },
})
